package com.example.demo.service;

import com.example.demo.dto.TokenResponse;
import com.example.demo.dto.UserInfoResponse;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.http.*;
@Service
public class DingService implements IDingService{

    @Value("${dingtalk.appkey}")
    private String appKey;

    @Value("${dingtalk.appsecret}")
    private String appSecret;

    private final RestTemplate restTemplate;

    public DingService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public UserInfoResponse getDingToken(String code) {
        String tokenUrl = "https://oapi.dingtalk.com/gettoken";

        // ==================get===============
        UriComponentsBuilder tokneBuilder = UriComponentsBuilder.fromHttpUrl(tokenUrl)
                .queryParam("appkey", appKey)
                .queryParam("appsecret", appSecret);

        // 调用接口并将响应转换为 TokenResponse 对象
        ResponseEntity<TokenResponse> response = restTemplate.getForEntity(tokneBuilder.toUriString(), TokenResponse.class);

        // =====================
        // 获取 判断  access_token 字段的值
        TokenResponse tokenResponse = response.getBody();
        String token = tokenResponse.getAccess_token();
        // token 通过token和code获取用户信息


        // ==================post===============
        String userInfo = "https://oapi.dingtalk.com/topapi/v2/user/getuserinfo";

        UriComponentsBuilder userInfoBuild = UriComponentsBuilder.fromHttpUrl(userInfo)
                .queryParam("access_token", token);
        String jsonBody = "{\"code\": \"" + code + "\"}";
        // 构建 HTTP 请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);

        // 发起 POST 请求并返回响应
        ResponseEntity<UserInfoResponse> userInfoResponse = restTemplate.exchange(
                userInfoBuild.toUriString(), HttpMethod.POST, entity, UserInfoResponse.class);
        // ==================post===============

        return userInfoResponse.getBody();
    }
}
